import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'package:flutter_learn_vi/src/bean/bean_day_stat.dart';
import 'package:flutter_learn_vi/src/net/dio_utils.dart';
import 'package:flutter_learn_vi/src/page/common/common_loading_dialog.dart';
import 'package:flutter_learn_vi/src/page/common/common_nodata_widget.dart';
import 'package:flutter_learn_vi/src/utils/navigator_utils.dart';
import 'package:flutter_learn_vi/src/utils/toast_utils.dart';

import '../new/score/mine_my_his_recoder_page.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2020/12/4.
///
/// 可关注公众号：我的大前端生涯   获取最新技术分享
/// 可关注网易云课堂：https://study.163.com/instructor/1021406098.htm
/// 可关注博客：https://blog.csdn.net/zl18603543572
///
/// 代码清单
class ExamineScoreRecoderPage extends StatefulWidget {
  final int configId;
  final int userId;

  const ExamineScoreRecoderPage({
    Key key,
    this.configId,
    this.userId,
  }) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _MineItem2State();
  }
}

class _MineItem2State extends State<ExamineScoreRecoderPage>
    with AutomaticKeepAliveClientMixin, TickerProviderStateMixin {
  StreamSubscription<String> _streamSubscription;

  //标签页面保活 或者称保持状态
  @override
  bool get wantKeepAlive => true;

  AnimationController _animationController;

  Animation<Offset> _animation;

  int _pageIndex = 1;
  int _pageSize = 30;
  int _totalPage = 0;

  bool _loading = true;
  ScrollController _scrollController = new ScrollController();

  @override
  void initState() {
    super.initState();

    _animationController = new AnimationController(
        vsync: this, duration: Duration(milliseconds: 1200));

    _animation = new Tween(begin: Offset(0, -1), end: Offset(0, 0)).animate(
        CurvedAnimation(
            curve: Curves.fastOutSlowIn, parent: _animationController));

    _scrollController.addListener(() {
      double offset = _scrollController.offset;
      if (offset >= _scrollController.position.maxScrollExtent / 3 * 2) {
        if ((_pageIndex) < _totalPage && !_loading) {
          _pageIndex++;
          getTopicHistoryist();
        }
      }
    });
    getTopicHistoryist();
  }

  @override
  void dispose() {
    _animationController.dispose();
    _streamSubscription.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);

    //一个列表 切记不要再使用 Scaffold
    //否则会拦截事件 失去滑动联动效果
    return Scaffold(
      appBar: AppBar(
        title: Text("答题记录"),
      ),
      body: Container(
        padding: EdgeInsets.only(top: 12),
        color: Colors.white,
        child: buildBody(),
      ),
    );
  }

  Widget buildBody() {
    if (_list.length == 0) {
      if (_loading) {
        return LoadingWidget();
      }
      return Container(
        child: NoDataWidget(
          text: "暂无数据",
        ),
      );
    }
    return RefreshIndicator(
      notificationPredicate: (ScrollNotification notifation) {
        //该属性包含当前ViewPort及滚动位置等信息
        return false;
      },
      onRefresh: () async {
        _pageIndex = 0;
        await getTopicHistoryist();
        ToastUtils.showToast("已刷新");
        return true;
      },
      child: Container(
        color: Color(0xfff7f7f7),
        child: ListView.builder(
          controller: _scrollController,
          //去除内边距
          padding: EdgeInsets.all(0),
          //列表子Item个数
          itemCount: _list.length,
          //每个子Item的布局构建
          itemBuilder: (BuildContext context, int index) {
            return buildBodyWidget(index);
          },
        ),
      ),
    );
  }

  //每个子Item的布局构建
  Widget buildBodyWidget(int index) {
    BeanDayStat beanDayStat = _list[index];
    String timeStr = "${beanDayStat.answerTime}秒";
    if (beanDayStat.answerTime > 60) {
      timeStr =
          "${beanDayStat.answerTime ~/ 60}分${(beanDayStat.answerTime % 60).toInt()}秒";
    }

    double obtainScore = beanDayStat.obtainScore / 10;

    return InkWell(
      onTap: () {
        NavigatorUtils.pushPage(
          context,
          MineMyScoreHisRecoderPage(
            extractingId: beanDayStat.extractingId,
          ),
        );
      },
      child: Container(
        margin: EdgeInsets.only(top: 10),
        padding: EdgeInsets.all(10),
        color: Colors.white,
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              width: 2,
              height: 14,
              margin: EdgeInsets.only(left: 10, right: 8, top: 2),
              color: Colors.blue,
            ),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: [
                  Row(
                    children: [
                      Text(
                        "考试时间",
                        style: TextStyle(
                          fontSize: 14,
                          color: Color(0xff333333),
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                      SizedBox(
                        width: 10,
                      ),
                      Text(
                        beanDayStat.createTime,
                        style: TextStyle(
                          fontSize: 14,
                          color: Color(0xff333333),
                          fontWeight: FontWeight.w600,
                        ),
                      )
                    ],
                  ),
                  SizedBox(height: 5),
                  Row(
                    children: [
                      Text(
                        "答题时间",
                        style: TextStyle(
                          fontSize: 14,
                          color: Color(0xff666666),
                          fontWeight: FontWeight.w400,
                        ),
                      ),
                      SizedBox(width: 10),
                      Text(
                        timeStr,
                        style: TextStyle(
                          fontSize: 14,
                          color: Color(0xff666666),
                          fontWeight: FontWeight.w400,
                        ),
                      )
                    ],
                  ),
                  Row(
                    children: [
                      Text(
                        "获取得分数",
                        style: TextStyle(
                          fontSize: 14,
                          color: Color(0xff666666),
                          fontWeight: FontWeight.w400,
                        ),
                      ),
                      SizedBox(
                        width: 10,
                      ),
                      Text(
                        "${obtainScore.toStringAsFixed(0)}分",
                        style: TextStyle(
                          fontSize: 14,
                          color: Color(0xff666666),
                          fontWeight: FontWeight.w400,
                        ),
                      )
                    ],
                  )
                ],
              ),
            ),
            Container(
              child: Icon(
                Icons.arrow_forward_ios,
                size: 14,
              ),
              margin: EdgeInsets.only(top: 6),
            )
          ],
        ),
      ),
    );
  }

  List<BeanDayStat> _list = [];

  ///查询我的答题记录
  Future<List<BeanDayStat>> getTopicHistoryist() async {
    Map<String, dynamic> monthMap = {
      "userId": widget.userId,
      "configId": widget.configId,
      "pageIndex": _pageIndex,
      "limit": _pageSize
    };

    ResponseInfo statisRresponseInfo = await DioUtils.instance.getRequest(
        url: HttpHelper.myExamineTopicHistoryUrl, queryParameters: monthMap);
    _list = [];
    _loading = false;
    if (statisRresponseInfo.success) {
      List list = statisRresponseInfo.data['list'];
      _totalPage = statisRresponseInfo.data['totalPage'];
      list.forEach((element) {
        _list.add(BeanDayStat.fromMap(element));
      });
      if (mounted) {
        setState(() {});
      }
      return _list;
    } else {
      ToastUtils.showToast(statisRresponseInfo.message);
      return _list;
    }
  }
}
